#include "TcpServer.h"
#include <FloraLogger.h>
TcpServer::TcpServer(QObject *parent)
    : QTcpServer(parent) {}

TcpServer::~TcpServer() {
    stopServer();
}

bool TcpServer::startServer(quint16 port) {
    if (this->listen(QHostAddress::AnyIPv4,port)) {
        LOG_DEBUG << "Server started on port" << this->serverAddress()<<this->serverPort();
        return true;
    } else {
        LOG_DEBUG << "Server failed to start";
        return false;
    }
}

void TcpServer::stopServer() {
    this->close();
    qDeleteAll(clients);
    clients.clear();
    clientInfo.clear();
}

void TcpServer::incomingConnection(qintptr socketDescriptor) {
    QTcpSocket *clientSocket = new QTcpSocket(this);

    if (clientSocket->setSocketDescriptor(socketDescriptor)) {
        QString clientIp = clientSocket->peerAddress().toString();
        quint16 clientPort = clientSocket->peerPort();

        clients.append(clientSocket);
        clientInfo[clientSocket] = qMakePair(clientIp, clientPort);

        connect(clientSocket, &QTcpSocket::readyRead, this, &TcpServer::onReadyRead);
        connect(clientSocket, &QTcpSocket::disconnected, this, &TcpServer::onDisconnected);

        LOG_DEBUG << "New client connected:" << clientIp << ":" << clientPort;
        emit clientConnected(clientIp, clientPort); // 发射客户端连接信号
    } else {
        delete clientSocket;
    }
}

void TcpServer::onReadyRead() {
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    if (clientSocket) {
        QByteArray data = clientSocket->readAll();
        QString clientIp = clientSocket->peerAddress().toString();
        quint16 clientPort = clientSocket->peerPort();
        LOG_DEBUG << "Received data from" << clientIp << ":" << clientPort << ":" << data;

        emit dataReceived(clientIp, clientPort, data); // 发射数据接收信号
    }
}

void TcpServer::onDisconnected() {
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    if (clientSocket) {
        QString clientIp = clientSocket->peerAddress().toString();
        quint16 clientPort = clientSocket->peerPort();

        clients.removeOne(clientSocket);
        clientInfo.remove(clientSocket);
        clientSocket->deleteLater();

        LOG_DEBUG << "Client disconnected:" << clientIp << ":" << clientPort;
        emit clientDisconnected(clientIp, clientPort); // 发射客户端断开信号
    }
}

void TcpServer::sendDataToClient(const QString &ip, quint16 port, const QByteArray &data) {
    for (QTcpSocket *clientSocket : clients) {
        if (clientInfo[clientSocket].first == ip && clientInfo[clientSocket].second == port) {
            clientSocket->write(data);
            clientSocket->flush();
            qDebug() << "Sent data to" << ip << ":" << port << ":" << data;
            break;
        }
    }
}

void TcpServer::sendDataToAllClients(const QByteArray &data) {
    for (QTcpSocket *clientSocket : clients) {
        clientSocket->write(data);
        clientSocket->flush();
    }
    LOG_DEBUG << "Sent data to all clients:" << data;
}
